// logger/logger.go
package logger

import (
	"io"
	"log"
	"os"
	"path/filepath"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
)

var (
	defaultLogger *Logger
)

func init() {
	// 确保日志目录存在
	if err := os.MkdirAll("logs/logs", 0755); err != nil {
		log.Fatalf("创建日志目录失败: %v", err)
	}

	// 同时输出到文件和控制台
	defaultLogger = NewLogger("logs", "error")
}

type Logger struct {
	logger *log.Logger
}

func NewLogger(baseDir, prefix string) *Logger {
	logDir := filepath.Join("logs", baseDir)
	logFileName := prefix + ".log"
	logFilePath := filepath.Join(logDir, logFileName)

	writer, err := rotatelogs.New(
		logFilePath+".%Y%m%d",
		rotatelogs.WithLinkName(logFilePath),
		rotatelogs.WithRotationTime(24*time.Hour),
		rotatelogs.WithMaxAge(7*24*time.Hour),
	)
	if err != nil {
		log.Fatalf("无法初始化日志记录器: %v", err)
	}

	// 同时输出到文件和控制台
	multiWriter := io.MultiWriter(os.Stdout, writer)
	logger := log.New(multiWriter, "", log.LstdFlags)

	return &Logger{logger: logger}
}

func (l *Logger) Info(args ...interface{}) {
	l.logger.Printf("[INFO] %v\n", args...)
}

func (l *Logger) Error(args ...interface{}) {
	l.logger.Printf("[ERROR] %v\n", args...)
}

// Info 记录信息日志的包级别函数
func Info(args ...interface{}) {
	defaultLogger.Info(args...)
}

// Error 记录错误日志的包级别函数
func Error(args ...interface{}) {
	defaultLogger.Error(args...)
}
